package com.xuelang.pipeline.app.pipeline.impl;

import com.xuelang.jadp.client.sys.dto.UserInfoDTO;
import com.xuelang.pipeline.app.pipeline.ChangeMgmtService;
import com.xuelang.pipeline.app.pipeline.converter.ChangeMgmtToDTOConverter;
import com.xuelang.pipeline.client.common.constant.Constant;
import com.xuelang.pipeline.client.common.request.PageParam;
import com.xuelang.pipeline.client.common.result.PageRecord;
import com.xuelang.pipeline.client.pipeline.dto.ChangeMgmtDTO;
import com.xuelang.pipeline.client.pipeline.dto.ChangeMgmtQuery;
import com.xuelang.pipeline.domain.pipeline.ChangeMgmt;
import com.xuelang.pipeline.domain.pipeline.service.ChangeMgmtDomainService;
import com.xuelang.sys.app.sys.UserManagerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>组件变更管理服务实现类</p>
 *
 * @author : yixin.lys
 * @date : 2024-08-02 14:13
 **/
@Slf4j
@Service
public class ChangeMgmtServiceImpl implements ChangeMgmtService {

    @Autowired
    private ChangeMgmtDomainService changeMgmtDomainService;

    @Autowired
    private UserManagerService userManagerService;

    @Override
    public PageRecord<ChangeMgmtDTO> page(PageParam<ChangeMgmtQuery> query) {
        PageRecord<ChangeMgmt> page = changeMgmtDomainService.page(query);
        return new PageRecord<>(
                page.getCurrentPage(),
                page.getPageSize(),
                page.getTotalCount(),
                page.getTotalPages(),
                page.getRecords().stream().map(ChangeMgmtToDTOConverter.INSTANCE::toDTO).collect(Collectors.toList())
        );
    }

    @Override
    public Boolean add(ChangeMgmtDTO toAdd) {
        return changeMgmtDomainService.add(ChangeMgmtToDTOConverter.INSTANCE.fromDTO(toAdd));
    }

    @Override
    public Boolean update(ChangeMgmtDTO toUpdate) {
        return changeMgmtDomainService.update(ChangeMgmtToDTOConverter.INSTANCE.fromDTO(toUpdate));
    }

    @Override
    public ChangeMgmtDTO queryById(String id) {
        ChangeMgmt changeMgmt = changeMgmtDomainService.queryById(id);
        ChangeMgmtDTO result = ChangeMgmtToDTOConverter.INSTANCE.toDTO(changeMgmt);
        String creatorId = result.getCreatorId();
        UserInfoDTO userById = userManagerService.getUserById(creatorId);
        if (Objects.isNull(userById)) {
            result.setCreator(Constant.UNKNOWN_USER);
        }else {
            result.setCreator(userById.getRealName());
        }
        return result;
    }

    @Override
    public Boolean removeById(String id) {
        return changeMgmtDomainService.removeById(id);
    }

    @Override
    public Boolean removeByComponentLabel(String componentLabel) {
        return changeMgmtDomainService.removeByComponentLabel(componentLabel);
    }
}
